<template>
  <div class="page-container" style="flex-direction: row">
    <div class="page-left fx-sk mg-rt-16 pd-24 bg-fff bd-rd-8">
      <TrTreeFilterVue
        ref="trTree"
        title="组织架构"
        :expandOnclickNode="true"
        :treeData="treeData"
        :defaultProps="defaultProps"
        showWord="title"
        @select-back="selectBack"
      />
    </div>
    <div class="page-right fx fx-cl bd-rd-8 fx-full wd-0">
      <div class="common-content-wrap">
        <TrTable
          ref="trTable"
          :btnList="btnList"
          :total="totalNum"
          v-model="searchParams"
          :searchShowList="searchShowList"
          :tableColumn="tableColumn"
          requestName="searchHandle"
          :tableData="tableData"
          @add="operateHandle($event, 'add')"
          @rowDelete="operateHandle($event, 'rowDelete')"
          @rowEdit="operateHandle($event, 'rowEdit')"
        />
      </div>
    </div>
    <TrEditPopup
      v-model="isShowEdit"
      :title="checkTitle"
      :width="460"
      :labelWidth="102"
      :valueObj.sync="formObj"
      :formData="formData"
      :list="popupList"
      @close="isShowEdit = false"
      @confrim="confrimHandle"
    />
  </div>
</template>

<script>
import { findByProperty } from "@/utils/util";
import TrEditPopup from "@/components/Tr-edit/Tr-edit-popup.vue";
import TrTable from "@/components/Tr-table/Tr-table.vue";
import TrTreeFilterVue from "@/components/Tr-tree-filter/Tr-tree-filter.vue";
import {
  getTreeList,
  add,
  remove,
  update,
  getLeftTreeList,
} from "@/api/baseCode/organizationalStructure";
import { getLevel } from "@/api/baseCode/organizationalHierarchy";
export default {
  name: "OrganizationalStructure",
  components: {
    TrEditPopup,
    TrTreeFilterVue,
    TrTable,
  },

  data() {
    return {
      defaultProps: {
        children: "children",
        label: "title",
      },
      formObj: {},
      formData: {},
      isShowEdit: false,
      popupList: [
        {
          label: "组织层级",
          type: "select",
          width: 100,
          value: "",
          id: "orgLevelId",
          list: [],
          disabled: false,
        },
        {
          label: "组织编码",
          type: "input",
          width: 100,
          value: "",
          id: "orgCode",
        },
        {
          label: "组织名称",
          type: "input",
          width: 100,
          value: "",
          id: "orgName",
        },
        {
          label: "组织描述",
          type: "input",
          width: 100,
          value: "",
          id: "orgDesc",
          isNeed: false,
        },
        {
          label: "父级组织名称",
          type: "select",
          width: 100,
          value: "",
          id: "parentId",
          list: [
            {
              label: "顶级",
              value: 0,
            },
          ],
          disabled: true,
          isNeed: false,
        },
      ],

      totalNum: 0,
      searchParams: {
        current: 1,
        size: 10,
      },
      tableData: [],
      searchShowList: [
        {
          label: "组织编码",
          type: "input",
          width: 33.33,
          value: "",
          id: "orgCode",
        },
        {
          label: "组织名称",
          type: "input",
          width: 33.33,
          value: "",
          id: "orgName",
        },
      ],
      btnList: [{ label: "新增", option: "add", color: "blue" }],
      tableColumn: [],
      tableColumnList: [
        { type: "text", label: "组织编码", value: "orgCode" },
        { type: "text", label: "组织名称", value: "orgName" },
        { type: "text", label: "组织描述", value: "orgDesc" },
        { type: "text", label: "组织层级", value: "orgLevelName" },
        { type: "text", label: "父级组织名称", value: "parentOrgName" },
        {
          type: "option",
          label: "操作",
          fixed: "right",
          width: 140,
          showBtnList: [
            { label: "编辑", option: "rowEdit" },
            { label: "删除", option: "rowDelete" },
          ],
        },
      ],
      treeData: [],

      treeDefaultParams: {
        current: 1,
        size: 1000,
        parentId: "",
      },

      parentId: "",
      currentHandle: null,
      currentRowValue: null,
      currentTreeNodeLevel: 0,
      levelList: [],
    };
  },
  watch: {
    currentTreeNodeLevel: {
      handler(newVal) {
        if (newVal == "FACTORY" || newVal === 0) {
          this.btnList = [{ label: "新增", option: "add", color: "blue" }];
          this.tableColumn = this.tableColumnList;
        } else {
          this.tableColumn = this.tableColumnList.slice(0, -1);
          this.btnList = [];
        }
      },
      immediate: true,
    },
  },
  computed: {
    checkTitle() {
      return this.currentHandle === "add" ? "新增" : "编辑";
    },
  },
  async mounted() {
    await this.getLevelCode();
    this.getleftTreeHandle();
  },
  methods: {
    async getLevelCode() {
      let { data } = await getLevel();
      this.levelList = data.data;
    },
    resetBack() {
      this.$refs.trTree.reset();
    },
    async getleftTreeHandle() {
      const { data } = await getLeftTreeList();
      // this.treeData = data.data.map((item) => {
      //   const fItem = this.levelList.find((val) => val.levelCode == item.code);
      //   return {
      //     ...item,
      //     title: `${item.title}(${fItem.levelName})`,
      //   };
      // });
      this.treeData = data.data;
      this.setTitleHandle(this.treeData);
    },
    setTitleHandle(list) {
      if (!list || !list.length) return;
      list.forEach((item) => {
        const fItem = this.levelList.find((val) => val.levelCode == item.code);
        item.title = `${item.title}(${fItem.levelName})`;
        if (item.children && item.children.length > 0) {
          this.setTitleHandle(item.children);
        }
      });
    },
    async getListHandle(params) {
      const { data } = await getTreeList({
        ...params,
        parentId: this.parentId,
      });
      if (data.code !== 200) return;

      this.$validateData(data.data.records);
      this.totalNum = data.data.total;
      this.tableData = data.data.records;
      this.tableData.forEach((item) => {
        item.isShowrowEdit =
          item.orgLevelCode == "LINE" || item.orgLevelCode == "EQUIPMENT";
        item.isShowrowDelete =
          item.orgLevelCode == "LINE" || item.orgLevelCode == "EQUIPMENT";
      });
    },
    async getLevelHandle() {
      const levelItem = findByProperty(this.popupList, "id", "orgLevelId");
      let list = [];
      if (this.currentTreeNodeLevel === 0) {
        list = this.levelList.filter((item) => item.levelCode == "FACTORY");
      } else if (this.currentTreeNodeLevel === "FACTORY") {
        list = this.levelList.filter((item) => item.levelCode == "WORKSHOP");
      }

      levelItem.list = list.map(({ levelName, id }) => ({
        label: levelName,
        value: id,
      }));

      levelItem.disabled = this.currentHandle === "rowEdit";
    },
    async operateHandle(val, type) {
      this.currentHandle = type;
      this.formData = type === "rowEdit" ? val : {};

      if (["add", "rowEdit"].includes(type)) {
        await this.getLevelHandle();
      }

      const actions = {
        add: () => {
          this.formData = { parentId: this.parentId || 0 };
          this.isShowEdit = true;
        },
        rowEdit: () => {
          this.currentRowValue = val;
          this.isShowEdit = true;
        },
        rowDelete: async () => {
          const content = val.hasChildren
            ? [this.$t("tip.deleteParentLevel")]
            : [this.$t("tip.deleteLevel")];
          const result = await this.$textShow({
            title: this.$t("tip.label"),
            content,
          });
          if (result) await this.removeHandle(val);
        },
      };

      actions[type]?.();
    },
    async removeHandle(val) {
      const { data } = await remove(val.id);
      if (data.code !== 200) return;
      this.$message.success(this.$t("msg.success"));
      this.resetBack();
      this.getListHandle(this.searchParams);
      this.getleftTreeHandle();
    },
    async confrimHandle() {
      const { currentHandle, formObj, currentRowValue } = this;
      let apiCall;

      if (currentHandle === "add") {
        apiCall = () => add(formObj);
      } else if (currentHandle === "rowEdit") {
        apiCall = () => update({ ...formObj, id: currentRowValue.id });
      } else {
        return;
      }

      const { data } = await apiCall();
      if (data.code !== 200) return;

      this.$message.success(this.$t("msg.success"));
      this.isShowEdit = false;
      this.resetBack();
      this.refreshData();
    },
    async refreshData() {
      this.searchParams.current = 1;
      this.getListHandle(this.searchParams);
      this.getleftTreeHandle();
    },
    searchHandle() {
      this.getListHandle(this.searchParams);
    },
    selectBack(data) {
      this.currentTreeNodeLevel = data.code;
      const parentItem = findByProperty(this.popupList, "id", "parentId");
      parentItem.list.push({
        label: data.title,
        value: data.id,
      });
      this.parentId = data.id;
      this.getListHandle(this.searchParams);
    },
  },
};
</script>
